<template>
	<div>
		<div>
			<label>选择年份:</label>
			<select v-model="selectedYear">
				<option v-for="year in years" :key="year" :value="year">{{ year }}</option>
			</select>
			<label>选择月份:</label>
			<select v-model="selectedMonth">
				<option v-for="month in 12" :key="month" :value="month">{{ month }}月</option>
			</select>
		</div>
		<!-- 加载中提示 -->
		<div v-if="loading">加载中...</div>
		<!-- 图表容器 -->
		<div class="chart-container">
			<div ref="chartContainer1" class="chart"></div>
			<div ref="chartContainer2" class="chart"></div>
		</div>
		<!-- 分析结果区域 -->
		<div class="analysis-container">
			<h3>年度分析</h3>
			<p>本年度总销售额: {{ totalAnnualSales }}</p>
			<ul>
				<li v-for="(growth, index) in quarterlyGrowth" :key="index">
					第{{ index + 1 }}季度: 销售额 {{ growth.totalSales }}, 环比增长
					{{ growth.growth !== Infinity ? growth.growth.toFixed(2) + '%' : '0%' }}
				</li>
			</ul>
		</div>
		<!-- 月度分析区域 -->
		<div class="monthly-analysis-container">
			<h3>月度分析</h3>
			<p>选择月份总销售额: {{ monthlyTotalSales }}</p>
			<p>最高销售额日：{{ maxSalesDay }}, 销售总金额：{{ maxSalesAmount }}</p>
			<p>销售额波动标准差: {{ salesStdDeviation.toFixed(2) }}(数值越大，波动越大)</p>

			<!-- <p>销售额波动标准差计算方法：首先计算每天销售额的平均值，然后计算每天销售额与平均值的差的平方和，最后求平方和的平均值的平方根。</p> -->
		</div>
	</div>
</template>

<script>
	import axios from 'axios';
	import * as echarts from 'echarts';

	export default {
		data() {
			return {
				selectedYear: new Date().getFullYear(),
				selectedMonth: new Date().getMonth() + 1,
				years: [2023, 2024, 2025, 2026],
				options1: {
					title: {
						text: '年度每月销售额'
					},
					tooltip: {},
					legend: {
						data: ['商品销售', '宠物服务']
					},
					xAxis: {
						type: 'category',
						data: []
					},
					yAxis: {
						type: 'value'
					},
					series: [{
							name: '商品销售',
							type: 'bar',
							data: []
						},
						{
							name: '宠物服务',
							type: 'bar',
							data: []
						}
					]
				},
				options2: {
					title: {
						text: '月每天的销售额'
					},
					tooltip: {},
					legend: {
						data: ['宠物商品销售', '预约销售额']
					},
					xAxis: {
						type: 'category',
						data: []
					},
					yAxis: {
						type: 'value'
					},
					series: [{
							name: '宠物商品销售',
							type: 'line',
							data: []
						},
						{
							name: '预约销售额',
							type: 'line',
							data: []
						}
					]
				},
				loading: false,
				error: null,
				chartInstance1: null,
				chartInstance2: null,
				monthlySalesData: [], // 年销售数据
				dailySalesData: [], // 月销售数据
				quarterlyGrowth: [], // 季度增长数据
				totalAnnualSales: 0, // 本年度总销售额
				monthlyTotalSales: 0, // 选择月份总销售额
				salesStdDeviation: 0, // 销售额标准差
				maxSalesDay: '', // 最大销售额日
				maxSalesAmount: 0 // 最大销售额金额
			};
		},
		methods: {
			renderCharts() {
				if (this.chartInstance1) {
					this.chartInstance1.dispose();
				}
				this.chartInstance1 = echarts.init(this.$refs.chartContainer1);
				this.chartInstance1.setOption(this.options1);

				if (this.chartInstance2) {
					this.chartInstance2.dispose();
				}
				this.chartInstance2 = echarts.init(this.$refs.chartContainer2);
				this.chartInstance2.setOption(this.options2);
			},
			fetchData() {
				this.loading = true;
				const token = localStorage.getItem('Authorization');
				if (!token) {
					alert('未授权访问');
					this.loading = false;
					return;
				}
				const headers = {
					'Content-Type': 'application/json',
					'Authorization': token
				};

				// 获取年度每个月的商品销售和宠物服务总盈利
				Promise.all([
					axios.get('http://localhost:8887/Order/selectMonthlyProfit', {
						params: {
							year: this.selectedYear
						},
						headers: headers
					}),
					axios.get('http://localhost:8887/Serviceappointment/selectMonthlyProfit', {
						params: {
							year: this.selectedYear
						},
						headers: headers
					})
				]).then(responses => {
					const orderData = responses[0].data.data;
					const serviceData = responses[1].data.data;

					const months = orderData.map(item => `${item.month}月`);
					const orderProfits = orderData.map(item => parseFloat(item.totalAmount));
					const serviceProfits = serviceData.map(item => parseFloat(item.totalAmount));

					this.options1.xAxis.data = months;
					this.options1.series[0].data = orderProfits;
					this.options1.series[1].data = serviceProfits;

					this.monthlySalesData = [...orderData, ...serviceData]; // 存储年销售数据

					this.loading = false;
					this.renderCharts();
					this.analyzeData(); // 分析数据
				}).catch(error => {
					console.error('获取年度每个月的总盈利失败:', error);
					alert('获取年度每个月的总盈利失败');
					this.loading = false;
				});

				// 获取每月每天的盈利
				axios.get('http://localhost:8887/Order/selectDailyProfit', {
						params: {
							year: this.selectedYear,
							month: this.selectedMonth
						},
						headers: headers
					})
					.then(response => {
						if (response.data && response.data.data && response.data.data.length > 0) {
							const days = response.data.data.map(item => `${item.day}日`);
							const profits = response.data.data.map(item => parseFloat(item.totalAmount));
							this.options2.xAxis.data = days;
							this.options2.series[0].data = profits;
							this.dailySalesData = response.data.data; // 存储月销售数据
						} else {
							alert('当前月份没有销售数据');
						}
					})
					.catch(error => {
						console.error('获取每月每天的盈利失败:', error);
						alert('获取每月每天的盈利失败');
					});

				// 获取预约销售额
				axios.get('http://localhost:8887/Serviceappointment/selectDailyProfit', {
						params: {
							year: this.selectedYear,
							month: this.selectedMonth
						},
						headers: headers
					})
					.then(response => {
						if (response.data && response.data.data && response.data.data.length > 0) {
							const days = response.data.data.map(item => `${item.day}日`);
							const appointmentProfits = response.data.data.map(item => parseFloat(item.totalAmount));
							this.options2.series[1].data = appointmentProfits;
							this.dailySalesData = this.dailySalesData.map((item, index) => ({
								...item,
								totalAmount: parseFloat(item.totalAmount) + appointmentProfits[index]
							})); // 计算总销售额
							this.calculateDailySales(); // 计算选择月份总销售额
							this.calculateSalesStdDeviation(); // 计算销售额标准差
						} else {
							alert('当前月份没有预约销售数据');
						}
						this.loading = false;
						this.renderCharts();
					})
					.catch(error => {
						console.error('获取预约销售额失败:', error);
						alert('获取预约销售额失败');
						this.loading = false;
					});
			},
			analyzeData() {
				try {
					const monthlyData = this.monthlySalesData;
					const quarters = {};
					let totalSales = 0;

					for (let i = 0; i < monthlyData.length; i++) {
						const month = monthlyData[i].month;
						const quarter = Math.floor((month - 1) / 3) + 1;
						const sales = parseFloat(monthlyData[i].totalAmount);

						if (!quarters[quarter]) {
							quarters[quarter] = {
								totalSales: 0,
								growth: 0
							};
						}

						quarters[quarter].totalSales += sales;
						totalSales += sales;
					}

					this.totalAnnualSales = totalSales; // 设置本年度总销售额

					const quarterGrowth = [];
					for (let i = 1; i <= 4; i++) {
						const currentQuarterTotal = quarters[i] ? quarters[i].totalSales : 0;
						let previousQuarterTotal = 0;
						if (i > 1) {
							previousQuarterTotal = quarters[i - 1] ? quarters[i - 1].totalSales : 0;
						}

						const growth = ((currentQuarterTotal - previousQuarterTotal) / previousQuarterTotal) * 100;
						quarterGrowth.push({
							totalSales: currentQuarterTotal,
							growth: growth
						});
					}

					this.quarterlyGrowth = quarterGrowth;
				} catch (error) {
					console.error('Error in analyzeData method:', error);
				}
			},
			calculateDailySales() {
				this.monthlyTotalSales = this.dailySalesData.reduce((acc, val) => acc + parseFloat(val.totalAmount), 0);
			},
			calculateSalesStdDeviation() {
				const dailySales = this.dailySalesData.map(item => parseFloat(item.totalAmount));
				const mean = dailySales.reduce((acc, val) => acc + val, 0) / dailySales.length;
				const variance = dailySales.reduce((acc, val) => acc + (val - mean) ** 2, 0) / dailySales.length;
				this.salesStdDeviation = Math.sqrt(variance);

				// 找到最大销售额日和金额
				const maxSales = dailySales.reduce((max, val, index) => {
					if (val > max.val) {
						max.val = val;
						max.index = index;
					}
					return max;
				}, {
					val: 0,
					index: -1
				});
				if (maxSales.index !== -1) {
					const maxDay = this.dailySalesData[maxSales.index];
					this.maxSalesDay = `${maxDay.day}日`;
					this.maxSalesAmount = maxDay.totalAmount;
				}
			}
		},
		watch: {
			selectedYear: function(newVal, oldVal) {
				this.fetchData();
			},
			selectedMonth: function(newVal, oldVal) {
				this.fetchData();
			}
		},
		mounted() {
			this.fetchData();
		}
	};
</script>

<style scoped>
	.chart-container {
		display: flex;
		justify-content: space-between;
		margin: 20px;
	}

	.chart {
		width: 45%;
		height: 400px;
		border: 1px solid #ccc;
		/* 更改边框颜色 */
	}

	.analysis-container {
		width:43%;
		margin: 20px;
		padding: 10px;
		border: 1px solid #ccc;
		background-color: #f9f9f9;
		float: left;
	}

	.monthly-analysis-container {
		width: 43%;
		margin: 20px;
		padding: 10px;
		border: 1px solid #ccc;
		background-color: #f9f9f9;
		float: right;
	}

	.analysis-container h3,
	.monthly-analysis-container h3 {
		margin-bottom: 10px;
	}

	.analysis-container ul,
	.monthly-analysis-container ul {
		list-style-type: none;
		padding: 0;
	}

	.analysis-container li,
	.monthly-analysis-container li {
		margin-bottom: 5px;
	}
</style>